﻿#region

using System.Collections.Generic;

#endregion

namespace Domain.Algorithms {
    public static class DecompositionTreeBuilder {
        public static Graph<Edge> BuildDecompositionTree(Graph<HyperEdge> H) {
            if (H.IsMAcyclic) {
                return BuildDecompositionTreForMAcyclicHyperGraph(H);
            }
            else {
                return BuildDecompositionTreForMCyclicHyperGraph(H);
            }
        }

        private static Graph<Edge> BuildDecompositionTreForMAcyclicHyperGraph(Graph<HyperEdge> H) {
            var edgedGraph = SupportGraphsBuilder.FindEdgedGraph(H);
            return Kruskal.FindSpaningTree(edgedGraph);
        }

        private static Graph<Edge> BuildDecompositionTreForMCyclicHyperGraph(Graph<HyperEdge> H) {
            var B = Graham.BuildReducedGraph(H);

            var blocks = new BlocksFinder(B).FindBlocks();
            var newEdges = new List<HyperEdge>();

            for (var i = 0; i < blocks.Count; i++) {
                var block = blocks[i];
                ToMAcyclicGraphCompleter.Complete(ref block, ref newEdges);
            }

            newEdges.ForEach(e => H.AddEdge(e));

            var edgedGraph = SupportGraphsBuilder.FindEdgedGraph(H);

            var spaningTree = Kruskal.FindSpaningTree(edgedGraph);

            return spaningTree;
        }
    }
}